package com.cy.pj.ajax.controller;

import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
public class AjaxController {
    private List<Map<String,Object >> data=new ArrayList<>();

    public AjaxController(){
        Map<String,Object> map=new HashMap<>();
        map.put("id", "100");
        map.put("name", "ajax");
        map.put("remark", "Very Good");
        data.add(map);
    }

//    @RequestMapping("/doAjaxGet")
    /**
     *  @GetMapping 表示只能处理get请求的映射
     *  等效于@RequestMapping(value="/doAjaxGet",method=RequestMethod.GET)
     *  请求方式不匹配会出现405异常
     */
    @CrossOrigin//此注解描述的方法允许跨域访问
    @GetMapping("/doAjaxGet")
    public List<Map<String,Object>> doAjaxGet(){
        return data;
    }

    @PostMapping("/doAjaxPost")
    public String doAjaxPost(@RequestParam Map<String,Object> map){
        data.add(map);
        return "Save Ok";
    }

    @PutMapping("/doAjaxUpdate")
    public String doAjaxUpdate(@RequestParam Map<String,Object> map){
        String id= (String) map.get("id");
        Iterator<Map<String,Object>> it=data.iterator();
        Map<String,Object> obj=null;
        while (it.hasNext()){
            obj=it.next();
            if(obj.get("id").equals(id))break;
        }
        obj.put("name", map.get("name"));
        obj.put("remark", map.get("remark"));
//        for (Map<String,Object> item:data){
//            if(item.get("id").equals(id)){
//                item.put("name", map.get("name"));
//                item.put("remark", map.get("remark"));
//            }
//        }
        return "Update Ok";
    }

    @DeleteMapping("/doAjaxDelete/{id}")
    public String doAjaxDelete(@PathVariable Integer id){
        Iterator<Map<String,Object>> it=data.iterator();
        while (it.hasNext()){
            Map<String,Object> map=it.next();
            if(map.get("id").equals(String.valueOf(id))){
                it.remove();//迭代的时候删除只能调用迭代器的remove方法
//                data.remove(id); 这样删除会发生并发异常
            }
        }
        return "Delete Ok";
    }

    @RequestMapping("/doAjaxStart")
    public String doAjaxStart(){
        return "Response Result Of Ajax Get Request 01";
    }
    @RequestMapping("/doNotAjaxStart")
    public String doNotAjaxStart(){
        return "not-ajax-01";
    }
}
